#!/bin/bash

# DTU项目构建脚本
# 支持三种DTU版本的编译：Ethernet-only, WiFi+Ethernet, 4G+Ethernet
# 使用CMake构建系统，支持调试和发布版本

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 项目配置
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
BUILD_DIR="$PROJECT_DIR/cmake-build-debug"

# 交叉编译工具链配置
ARM_LINUX_TOOLCHAIN_PREFIX="arm-linux-gnueabihf-"
X64_LINUX_TOOLCHAIN_PREFIX="x86_64-linux-gnu-"

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_debug() {
    echo -e "${BLUE}[DEBUG]${NC} $1"
}

# 显示帮助信息
show_help() {
    echo "=========================================="
    echo "    DTU项目构建脚本 v1.0"
    echo "=========================================="
    echo ""
    echo "用法: $0 [选项]"
    echo ""
    echo "DTU版本选项:"
    echo "  --ethernet      编译纯网口版本（默认）"
    echo "  --wifi          编译WiFi+网口版本"
    echo "  --4g            编译4G+网口版本"
    echo ""
    echo "构建选项:"
    echo "  -h, --help      显示此帮助信息"
    echo "  -c, --clean     清理构建目录后重新构建"
    echo "  -r, --release   发布版本构建（优化，用于生产环境）"
    echo "  -d, --debug     调试版本构建（默认，用于开发调试）"
    echo "  -t, --tests     编译测试程序"
    echo ""
    echo "目标平台选项:"
    echo "  --target-linux-arm    交叉编译为Linux ARM（适用于LD1等开发板）"
    echo "  --target-linux-x64    交叉编译为Linux x86_64"
    echo "  --target-native       本地编译（默认）"
    echo ""
    echo "常用示例:"
    echo "  $0                              # 编译默认版本（纯网口，调试模式）"
    echo "  $0 --wifi                       # 编译WiFi+网口版本"
    echo "  $0 --4g --release               # 编译4G+网口发布版本"
    echo "  $0 --4g --release --target-linux-arm  # 为LD1开发板编译4G版本"
    echo "  $0 --clean --wifi --target-linux-arm  # 清理后为ARM Linux编译WiFi版本"
    echo ""
    echo "输出文件:"
    echo "  可执行文件: cmake-build-debug/bin/iot_dtu_c"
    echo "  配置文件: config/dtu_config.ini"
    echo ""
    echo "注意事项:"
    echo "  - 发布版本用于刷写到开发板"
    echo "  - 调试版本用于本地开发和测试"
    echo "  - 编译前请确保已安装CMake和GCC"
    echo "  - 交叉编译需要安装对应的工具链"
    echo "  - LD1开发板请使用 --target-linux-arm 选项"
    echo ""
}

# 清理构建目录
clean_build() {
    log_info "清理构建目录..."
    if [[ -d "$BUILD_DIR" ]]; then
        rm -rf "$BUILD_DIR"
        log_info "构建目录已清理"
    fi
}

# 创建构建目录
create_build_dir() {
    if [[ ! -d "$BUILD_DIR" ]]; then
        log_info "创建构建目录: $BUILD_DIR"
        mkdir -p "$BUILD_DIR"
    fi
}

# 检查交叉编译工具链
check_cross_toolchain() {
    local target="$1"
    local toolchain_prefix=""

    case "$target" in
        "linux-arm")
            toolchain_prefix="$ARM_LINUX_TOOLCHAIN_PREFIX"
            ;;
        "linux-x64")
            toolchain_prefix="$X64_LINUX_TOOLCHAIN_PREFIX"
            ;;
        "native")
            return 0
            ;;
        *)
            log_error "不支持的目标平台: $target"
            return 1
            ;;
    esac

    # 检查编译器是否存在
    if ! command -v "${toolchain_prefix}gcc" >/dev/null 2>&1; then
        log_error "未找到交叉编译工具链: ${toolchain_prefix}gcc"
        case "$target" in
            "linux-arm")
                log_info "安装ARM Linux工具链:"
                log_info "  macOS: brew install arm-linux-gnueabihf-binutils"
                log_info "  Ubuntu: sudo apt-get install gcc-arm-linux-gnueabihf"
                ;;
            "linux-x64")
                log_info "安装x64 Linux工具链:"
                log_info "  macOS: brew install x86_64-linux-gnu-binutils"
                log_info "  Ubuntu: sudo apt-get install gcc-x86-64-linux-gnu"
                ;;
        esac
        return 1
    fi

    log_info "找到交叉编译工具链: ${toolchain_prefix}gcc"
    return 0
}

# 配置CMake
configure_cmake() {
    local cmake_args=()

    # 添加生成器
    cmake_args+=("-G" "Unix Makefiles")

    # 添加构建类型
    if [[ "$BUILD_TYPE" == "Release" ]]; then
        cmake_args+=("-DCMAKE_BUILD_TYPE=Release")
    else
        cmake_args+=("-DCMAKE_BUILD_TYPE=Debug")
    fi

    # 添加测试选项
    if [[ "$BUILD_TESTS" == "ON" ]]; then
        cmake_args+=("-DBUILD_TESTS=ON")
    fi

    # 添加设备型号选项
    if [[ -n "$DEVICE_MODEL" ]]; then
        case "$DEVICE_MODEL" in
            "ethernet")
                cmake_args+=("-DBUILD_ETHERNET_ONLY=ON")
                ;;
            "wifi")
                cmake_args+=("-DBUILD_WIFI_ETHERNET=ON")
                ;;
            "4g")
                cmake_args+=("-DBUILD_4G_ETHERNET=ON")
                ;;
        esac
    fi

    # 添加交叉编译配置
    if [[ -n "$TARGET_PLATFORM" && "$TARGET_PLATFORM" != "native" ]]; then
        case "$TARGET_PLATFORM" in
            "linux-arm")
                cmake_args+=("-DCMAKE_SYSTEM_NAME=Linux")
                cmake_args+=("-DCMAKE_SYSTEM_PROCESSOR=arm")
                cmake_args+=("-DCMAKE_C_COMPILER=${ARM_LINUX_TOOLCHAIN_PREFIX}gcc")
                cmake_args+=("-DCMAKE_CXX_COMPILER=${ARM_LINUX_TOOLCHAIN_PREFIX}g++")
                cmake_args+=("-DCMAKE_FIND_ROOT_PATH_MODE_PROGRAM=NEVER")
                cmake_args+=("-DCMAKE_FIND_ROOT_PATH_MODE_LIBRARY=ONLY")
                cmake_args+=("-DCMAKE_FIND_ROOT_PATH_MODE_INCLUDE=ONLY")
                # 修改构建目录以区分不同平台
                BUILD_DIR="$PROJECT_DIR/cmake-build-linux-arm"
                ;;
            "linux-x64")
                cmake_args+=("-DCMAKE_SYSTEM_NAME=Linux")
                cmake_args+=("-DCMAKE_SYSTEM_PROCESSOR=x86_64")
                cmake_args+=("-DCMAKE_C_COMPILER=${X64_LINUX_TOOLCHAIN_PREFIX}gcc")
                cmake_args+=("-DCMAKE_CXX_COMPILER=${X64_LINUX_TOOLCHAIN_PREFIX}g++")
                cmake_args+=("-DCMAKE_FIND_ROOT_PATH_MODE_PROGRAM=NEVER")
                cmake_args+=("-DCMAKE_FIND_ROOT_PATH_MODE_LIBRARY=ONLY")
                cmake_args+=("-DCMAKE_FIND_ROOT_PATH_MODE_INCLUDE=ONLY")
                # 修改构建目录以区分不同平台
                BUILD_DIR="$PROJECT_DIR/cmake-build-linux-x64"
                ;;
        esac
    fi

    # 添加编译命令导出
    cmake_args+=("-DCMAKE_EXPORT_COMPILE_COMMANDS=ON")
    
    log_info "配置CMake..."
    log_debug "CMake参数: ${cmake_args[*]}"
    
    cd "$BUILD_DIR"
    if cmake "${cmake_args[@]}" ..; then
        log_info "CMake配置成功"
        return 0
    else
        log_error "CMake配置失败"
        return 1
    fi
}

# 编译项目
build_project() {
    log_info "开始编译项目..."
    
    cd "$BUILD_DIR"
    if make -j$(nproc 2>/dev/null || echo 4); then
        log_info "编译成功"
        
        # 复制compile_commands.json到项目根目录
        if [[ -f "compile_commands.json" ]]; then
            cp compile_commands.json "$PROJECT_DIR/"
            log_info "已更新compile_commands.json"
        fi
        
        return 0
    else
        log_error "编译失败"
        return 1
    fi
}

# 显示构建结果
show_results() {
    echo ""
    log_info "=== 构建结果 ==="
    
    if [[ -f "$BUILD_DIR/bin/iot_dtu_c" ]]; then
        local size=$(stat -f%z "$BUILD_DIR/bin/iot_dtu_c" 2>/dev/null || stat -c%s "$BUILD_DIR/bin/iot_dtu_c" 2>/dev/null)
        log_info "主程序: $BUILD_DIR/bin/iot_dtu_c ($size 字节)"
    fi
    
    if [[ "$BUILD_TESTS" == "ON" ]]; then
        if [[ -f "$BUILD_DIR/test_memory" ]]; then
            log_info "内存测试: $BUILD_DIR/test_memory"
        fi
        if [[ -f "$BUILD_DIR/test_modbus_basic" ]]; then
            log_info "Modbus测试: $BUILD_DIR/test_modbus_basic"
        fi
    fi
    
    echo ""
    log_info "=== 运行命令 ==="
    log_info "运行程序: cd $PROJECT_DIR && ./cmake-build-debug/bin/iot_dtu_c --test-mode"
    log_info "查看帮助: ./cmake-build-debug/bin/iot_dtu_c --help"
    log_info "Web界面: http://localhost:10020"
    
    if [[ "$BUILD_TESTS" == "ON" ]]; then
        echo ""
        log_info "=== 测试命令 ==="
        log_info "内存测试: ./cmake-build-debug/test_memory"
        log_info "Modbus测试: ./cmake-build-debug/test_modbus_basic"
    fi
}

# 主函数
main() {
    # 默认参数
    BUILD_TYPE="Debug"
    BUILD_TESTS="OFF"
    CLEAN_BUILD=false
    DEVICE_MODEL=""
    TARGET_PLATFORM="native"
    
    # 解析命令行参数
    while [[ $# -gt 0 ]]; do
        case $1 in
            -h|--help)
                show_help
                exit 0
                ;;
            -c|--clean)
                CLEAN_BUILD=true
                shift
                ;;
            -t|--tests)
                BUILD_TESTS="ON"
                shift
                ;;
            -r|--release)
                BUILD_TYPE="Release"
                shift
                ;;
            -d|--debug)
                BUILD_TYPE="Debug"
                shift
                ;;
            --ethernet)
                DEVICE_MODEL="ethernet"
                shift
                ;;
            --wifi)
                DEVICE_MODEL="wifi"
                shift
                ;;
            --4g)
                DEVICE_MODEL="4g"
                shift
                ;;
            --target-linux-arm)
                TARGET_PLATFORM="linux-arm"
                shift
                ;;
            --target-linux-x64)
                TARGET_PLATFORM="linux-x64"
                shift
                ;;
            --target-native)
                TARGET_PLATFORM="native"
                shift
                ;;
            *)
                log_error "未知选项: $1"
                show_help
                exit 1
                ;;
        esac
    done
    
    echo -e "${BLUE}=== DTU项目构建脚本 ===${NC}"
    echo "项目目录: $PROJECT_DIR"
    echo "构建目录: $BUILD_DIR"
    echo "构建类型: $BUILD_TYPE"
    echo "编译测试: $BUILD_TESTS"
    echo "目标平台: $TARGET_PLATFORM"
    if [[ -n "$DEVICE_MODEL" ]]; then
        echo "设备型号: $DEVICE_MODEL"
    fi
    echo ""
    
    # 检查项目目录
    cd "$PROJECT_DIR"
    if [[ ! -f "CMakeLists.txt" ]]; then
        log_error "未找到CMakeLists.txt文件，请确认在正确的项目目录中"
        exit 1
    fi

    # 检查交叉编译工具链
    if ! check_cross_toolchain "$TARGET_PLATFORM"; then
        exit 1
    fi
    
    # 清理构建目录（如果需要）
    if [[ "$CLEAN_BUILD" == true ]]; then
        clean_build
    fi
    
    # 创建构建目录
    create_build_dir
    
    # 配置CMake
    if ! configure_cmake; then
        exit 1
    fi
    
    # 编译项目
    if ! build_project; then
        exit 1
    fi
    
    # 显示结果
    show_results
    
    log_info "构建完成！"
}

# 运行主函数
main "$@"
